package com.example.blog.Service;

import com.example.blog.mapper.ArticleMapper;
import com.example.blog.repository.ArticleRepository;
import com.example.blog.repository.LikesRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.blog.entity.likes;
import com.example.blog.entity.Article;
@Service
public class LikesService {

    @Autowired
    private LikesRepository likesRepository;
    @Autowired
    private ArticleRepository articleRepository;
    @Autowired
    private ArticleMapper articleMapper;
    public boolean likeArticle(int articleId, int userId) {

        Article article = articleRepository.findArticleById(articleId);
        System.out.println(article.getTitle());
        likes existingLike = likesRepository.findByArticleIdAndUserId(articleId, userId);
        if (existingLike != null && existingLike.getStatus() == 1) {
            // 已经是点赞状态，不做任何操作
            return false;
        } else if (existingLike != null && existingLike.getStatus() == 0) {
            // 之前是取消点赞状态，现在重新点赞
            article.setLikes(article.getLikes()+1);
            existingLike.setStatus(1);
            likesRepository.save(existingLike);
        } else {
            article.setLikes(article.getLikes()+1);
            System.out.println(article.getLikes());
            System.out.println(article.getTitle());
            System.out.println(article.getContent());
            likes newLike = new likes();
            newLike.setArticleId(articleId);
            newLike.setUserId(userId);
            newLike.setStatus(1);
            likesRepository.save(newLike);
        }
        return true;
    }

    public boolean unlikeArticle(int articleId, int userId) {
        likes existingLike = likesRepository.findByArticleIdAndUserId(articleId, userId);
        Article article = articleMapper.selectArticleById(articleId);
        if (existingLike != null && existingLike.getStatus() == 1) {
            article.setLikes(article.getLikes()-1);
            existingLike.setStatus(0);
            likesRepository.save(existingLike);
            return true;
        }
        // 如果已经是取消点赞状态，不做任何操作
        return false;
    }
}